package org.galaxyworld.flycode.model;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;
import org.galaxyworld.flycode.config.AppConfig;
import org.galaxyworld.flycode.utils.NameUtils;

@ToString
public class Field {

    @Setter @Getter
    private String tableName;

    @Setter @Getter
    private String columnType;

    @Setter @Getter
    private String shortColumnType;

    @Setter @Getter
    private String columnName;

    @Setter @Getter
    private String constraintType;

    private String codeType;

    private String codeName;

    public boolean isPrimaryKey() {
        return "PRIMARY KEY".equalsIgnoreCase(constraintType);
    }

    public String getCodeType() {
        if (StringUtils.isBlank(codeType)) {
            codeType = getSourceCodeType();
        }
        return codeType;
    }

    public String getCodeName() {
        if (StringUtils.isBlank(codeName)) {
            codeName = NameUtils.columnNameToMemberName(columnName);
        }
        return codeName;
    }

    private String getSourceCodeType() {
        String type = StringUtils.lowerCase(shortColumnType);
        switch (type) {
            case "bit":
            case "boolean":
                return "Boolean";
            case "tinyint":
            case "smallint":
            case "integer":
                return "Integer";
            case "bigint":
                return "Long";
            case "float":
            case "real":
            case "double":
            case "numeric":
            case "decimal":
                return "Double";
            case "char":
            case "varchar":
            case "longvarchar":
            case "nchar":
            case "nvarchar":
            case "longnvarchar":
                return "String";
            case "date":
            case "time":
            case "datetime":
            case "timestamp":
                return AppConfig.isJava8() ? "LocalDateTime" : "Date";
            default:
                return "String";
        }
    }
}
